package com.order.service.impl;

import com.order.constant.MessageConstant;
import com.order.dto.UserLoginDTO;
import com.order.entity.User;
import com.order.exception.AccountAlreadyExistException;
import com.order.exception.PasswordErrorException;
import com.order.mapper.UserMapper;
import com.order.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.order.exception.AccountNotFoundException;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();


        User user = userMapper.getByUsername(username);

        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if(user.getStatus() == 0){
            //账号被禁用
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }

        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!user.getPassword().equals(password)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    @Override
    public void register(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        if (user == null) {
            //账号不存在
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
        }else{
            throw new AccountAlreadyExistException(MessageConstant.ALREADY_EXISTS);
        }
    }
}
